package it.unibo.mumu.util;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import it.unibo.mumu.R;
import it.unibo.mumu.entity.Universe;

public class ListAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<Universe> objects;

    public ListAdapter(Context context, ArrayList<Universe> products) {
        ctx = context;
        objects = products;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return objects.size();
    }

    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }

        Universe u = getUniverse(position);

        ((TextView) view.findViewById(R.id.universeDescription)).setText(u.getName());
        ((TextView) view.findViewById(R.id.universeSize)).setText("Dimensione: "+u.getSize() + "MB");
        ((ImageView) view.findViewById(R.id.universeAvatar)).setImageResource(0);
        
        // imposta relativa immagine di avatar
        File imgFile =  new  File("data/data/it.unibo.mumu/files/"+u.getAvatarpath());
        if(imgFile.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            ImageView myImage = (ImageView) view.findViewById(R.id.universeAvatar);
            myImage.setImageBitmap(myBitmap);
        }

        CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
        cbBuy.setOnCheckedChangeListener(myCheckChangList);
        cbBuy.setTag(position);
        cbBuy.setChecked(u.getBox());
        return view;
    }

    Universe getUniverse(int position) {
        return ((Universe) getItem(position));
    }

    public ArrayList<Universe> getBox() {
        ArrayList<Universe> box = new ArrayList<Universe>();
        for (Universe p : objects) {
            if (p.getBox())
                box.add(p);
        }
        return box;
    }

    OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            getUniverse((Integer) buttonView.getTag()).setBox(isChecked);
        }
    };
}
